// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Common");

/*
 * 定义一个基础弹窗组件，该弹窗只创建弹窗容器，并提供显示，隐藏和销毁功能
 */
yepjs.define("popWin", {

    NS: "YBA.Plugin",

    field: (function () {

        var baseZindex = 999;

        var PopWin = function (options) {

            // 创建弹窗对象
            var self = this.self = $(document.createElement("div"));
            this.self.css({ display: "none", position: "fixed" });

            // 创建对应的覆盖层对象
            if(!options.nomask){
                this.mask = $(document.createElement("div"));
                this.mask.addClass("ui-mask");
                this.mask.css({ "zIndex": ++baseZindex});
            }

            this.self.attr({ "id": "yba_popwin_" + (new Date()).getTime(), "class": "ui-dialog" });
            this.self.css("zIndex", ++baseZindex);

            // 是否在关闭弹窗时销毁
            this._destroy = options.destroy || true;

            // 隐藏弹窗后的回调
            this._onHide = options.onHide;

            // 显示弹窗后的回调
            this._onShow = options.onShow;

            // 插入到body中
            $(document.body).append(this.mask).append(this.self);

        };

        /*
         * 显示弹窗
         */
        PopWin.prototype.show = function () {

            this._onShow && this._onShow(this);

            YBA.Common.setCenter(this.self);

            this.mask && this.mask.show();

            // 使弹窗居中显示并获取焦点
            this.self.show().focus();

            return this;
        }

        /*
         * 隐藏弹窗
         */
        PopWin.prototype.hide = function (nohidecallback) {
            this.self.hide();
            this.mask && this.mask.hide();
            if(nohidecallback !== false){
                this._onHide && this._onHide(this);
            }
            this._destroy && this.destroy();
            return this;
        }

        /*
         * 销毁弹窗
         */
        PopWin.prototype.destroy = function () {
            this.self.html("");
            this.mask && this.mask.remove();
            this.self.remove();
        }

        return PopWin;
    })()
});

/*
 * 定义一个带头部和按钮的弹窗组件，继承自YBA.Plugin.popWin
 */
yepjs.define("popform", {

    NS: "YBA.Plugin",

    field: (function () {

        var popform = function (options) {

            var options = options || {},
                t = new YBA.Plugin.popWin(options);

            // 给弹窗对象添加一个自定义的className
            options.className && t.self.addClass(options.className);

            // 头部
            t.head = $(document.createElement("div"));
            t.head.attr({ "class": "ui-dialog-header" });

            // 创建右上角关闭按钮
            t.close = $(document.createElement("i"));
            t.close.attr({ "class": "ui-dialog-close" });

            // 绑定关闭按钮事件
            t.close.click(function () {
                t.hide();
            });

            t.head.append(t.close);

            // 创建标题区
            t.title = $(document.createElement("span"));
            t.title.addClass("ui-dialog-title");
            options.title && t.title.html(options.title);
            t.head.append(t.title);

            // 创建内容区
            t.content = $(document.createElement("div"));
            t.content.addClass("ui-dialog-content");
            t.contbody = $(document.createElement("div"));
            t.contbody.addClass("ui-dialog-contbody");

            options.content && t.contbody.html(options.content);

            // 将标题和内容区添加到主弹窗对象中
            t.self.append(t.head);
            t.content.append(t.contbody);
            t.self.append(t.content);

            // 创建按钮区
            // 未传入按钮参数则不创建
            if (options.btns && options.btns.length > 0) {

                t.btnCon = $(document.createElement("div"));
                t.btnCon.addClass("ui-dialog-btns");

                // 循环生成按钮
                for (var i = 0, l = options.btns.length; i < l; i++) {

                    (function (i) {

                        var btn = $(document.createElement("input"));
                        btn.attr({ "type": "button" });

                        options.btns[i].className && btn.addClass(options.btns[i].className);
                        options.btns[i].value && btn.val(options.btns[i].value);

                        options.eventName = options.eventName || "click";
                        options.btns[i].fn && btn.bind(options.eventName, options.btns[i].fn);

                        t.btnCon.append(btn);
                    })(i);
                }

                // 将按钮区添加到主弹窗对象中
                t.content.append(t.btnCon);
            }

            // 设置高宽
            options.width && t.self.css("width", options.width);
            options.height && t.self.css("height", options.height);

            // 绑定拖动事件
            YBA.Common.drag(t.head, t.self);

            // 给覆盖层绑定点击事件
            // 使标题区闪烁
            t.mask.bind("mousedown", function () {
                var head = t.head;
                var i = 0, timer;
                timer = setInterval(function () {
                    if (i % 2 == 0) {
                        head.addClass("ui-header-grey");
                    } else {
                        head.removeClass("ui-header-grey");
                    }
                    i++;
                    if (i > 5) {
                        clearInterval(timer);
                    }
                }, 100);
            });

            for (var p in t) {
                this[p] = t[p];
            }
        };

        /*
         * 设置标题
         * @title:要设置的标题，会替换原来的标题
         */
        popform.prototype.setTitle = function (title) {
            this.title.html(title);
            return this;
        }

        /*
         * 设置内容
         * @content:要设置的内容
         */
        popform.prototype.setContent = function (content) {
            this.conbody.html(content);
            return this;
        }

        return popform;

    })()
});

/*
 * 定义一个操作确认弹窗，基于YBA.Plugin.popform
 */
yepjs.define("confirm", {

    NS: "YBA.Plugin",

    field: function (options) {

        options.title = options.title || "提示";
        options.type = options.type || "i";

        var tipType = {
            i: "warning",
            o: "success",
            e: "error",
            q: "query"
        };

        var confirm = new YBA.Plugin.popform({
            title: options.title,
            className: "ui-confirm",
            content: '<div class="ui-confirm-content"><i class="ui-ico ui-ico-' + tipType[options.type] + '"></i>' + options.msg + '</div>',
            width: 330,
            height: options.height || "auto",
            destroy: true,
            onHide: options.onHide || null,
            onShow: options.onShow || null,
            btns: [{
                value: options.btnTxt1 || "删除",
                className: "btn blue g-mr10",
                fn: function () {
                    if (options.yes) {
                        options.yes.call(confirm);
                    }
                }
            }, {
                value: options.btnTxt2 || "取消",
                className: "btn red g-ml10",
                fn: function () {
                    if (options.no) {
                        if (options.no.call(confirm) === false) {
                            return;
                        } else {
                            confirm.hide();
                        }
                    } else {
                        confirm.hide();
                    }
                }
            }]
        });
        confirm.show();

        return confirm;
    }
});

/*
 * 定义一个全局等待状态对象
 *
 * 示例：
 * YBA.Plugin.loading.show()
 * YBA.Plugin.loading.show("提示信息")
 * YBA.Plugin.loading.hide()
 */
yepjs.define("loading", {

    NS: "YBA.Plugin",

    field: (function () {

        var loading;

        return {

            /*
             * 显示等待状态
             * @msg：可选参数，要显示的提示信息
             */
            show: function (msg) {
                if (!loading) {
                    loadingBg = $(document.createElement("div"));
                    loading = $(document.createElement("div"));
                    loadingBg.css({ position: "fixed" ,left:0,right:0,top:0,bottom:0,background:"#000",opacity:0.5,zIndex:999999999});
                    loading.css({ position: "absolute",zIndex:1000000000});
                    loading.attr("id", "yepjs_loading");
                    loading.addClass("ui-loading");
                    loading.append("<div>" + (msg || "请求中，请稍候...") + "</div>");
                    $(document.body).append(loading);
                    $(document.body).append(loadingBg);
                } else {
                    loading.html("<div>" + (msg || "请求中，请稍候...") + "</div>");
                }
                YBA.Common.setCenter(loading);
                loading.stop().fadeIn();
                loadingBg.stop().fadeIn();
            },

            // 隐藏等待状态
            hide: function () {
                loading && loading.stop().fadeOut();
                loadingBg && loadingBg.stop().fadeOut();
            }
        }
    })()
});

/*
 * 信息提示
 * @options:{
 *     type:         信息提示类型，可取"i/o/e/q"四个值，警告i，正确o，错误e，问号q
 *     msg:          可选参数，提示文字
 *     timeout:      可选参数，多长时间自动隐藏，默认为2000毫秒
 *     showCallback: 可选参数，提示显示出来后的回调函数
 *     hideCallback: 可选参数，提示隐藏后的回调函数
 * }
 *
 * 示例：
 * YBA.Plugin.msgtip({ type:"i", msg:"请输入密码", hideCallback:function(){ alert("隐藏") } });
 */
yepjs.define("msgtip", {

    NS: "YBA.Plugin",

    field: (function () {

        var tipType = {
            i: "warning",
            o: "success",
            e: "error",
            q: "query"
        };

        var msgtip, isvisible = false, timer;

        return function (options) {

            var options = options || {},
                type = tipType[options.type],
                timeout = options.timeout || 1200,
                msg = options.msg || "出错了！";

            clearTimeout(timer);

            if (!msgtip) {
                msgtip = $(document.createElement("div"));
                msgtip.addClass("ui-msgtip");
                msgtip.html("<div><i class='ui-ico ui-ico-" + type + "'></i>" + msg + "</div>");
                $(document.body).append(msgtip);

                msgtip.click(function () {
                    clearTimeout(timer);
                    msgtip.animate({ marginTop: -50, opacity: 0 }, function () {
                        msgtip.hide();
                        if (options.hideCallback) {
                            options.hideCallback();
                        }
                    });
                });
            } else {
                msgtip.html("<div><i class='ui-ico ui-ico-" + type + "'></i>" + msg + "</div>");
            }

            YBA.Common.setCenter(msgtip);
            msgtip.css({ "margin-top": 50, opacity: 0 });
            msgtip.show().animate({ "margin-top": 0, opacity: 1 }, function () {
                if (options.showCallback) {
                    options.showCallback();
                }
            });

            timer = setTimeout(function () {
                msgtip.animate({ marginTop: -50, opacity: 0 }, function () {
                    msgtip.hide();
                    if (options.hideCallback) {
                        options.hideCallback();
                    }
                });
            }, timeout);

            return msgtip;
        };

    })()
});

/*
 * 复选框全选
 */
yepjs.define("checkAll", {

    NS: "YBA.Plugin",

    field: function (options) {
        var op = options || {};
        op.allObj.bind("click", function () {
            op.eachObj = op.list.find(".j-checkEach");
            if (op.allObj.is(":checked")) {
                op.eachObj.prop("checked", true);
            } else {
                op.eachObj.prop("checked", false);
            }

            op.callback && op.callback();
        });

        op.eachObj.delegate(op.list,"click", function () {
            var t = $(this);
            if (t.is(":checked")) {
                if (op.eachObj.filter(":checked").length === op.eachObj.length) {
                    op.allObj.prop("checked", true);
                }
            } else {
                op.allObj.prop("checked", false);
            }

            op.callback && op.callback();
        });
    }
});

/*
 ** 定义一个带占位符的文本框
 */
yepjs.define("placeHolder", {

    NS: "YBA.Plugin",

    field: function(options) {
        var op = options || {};
        op.con.each(function() {
            var t = $(this),
                input = t.find("input"),
                holder = t.find("span");
            input.focus(function() {
                //holder.hide();
            }).blur(function() {
                if (input.val() === "") {
                    holder.show();
                } else {
                    holder.hide();
                }
            }).focus(function() {
                if (input.val() === "") {
                    holder.hide();
                }
            });
            setTimeout(function() {
                input.trigger("keyup");
            }, 1000);
        });
    }
});

/*
 * 分页组件
 */
yepjs.define("pageNav", {

    NS: "YBA.Plugin",

    field: (function (options) {

        var pageNav = function (options) {

            var op = options || {};

            // 总数量
            if (typeof op.totalNum === "undefined" || !/^\d+$/.test(op.totalNum)) {
                throw new Error("参数错误：totalNum应该为合法数字");
            }

            // 点击某一页的回调函数
            if (typeof op.callback !== "function") {
                throw new Error("参数错误：未传递回调函数");
            }

            // 每页数量
            this.pageSize = op.pageSize || 10;

            // 总数量
            this.totalNum = op.totalNum || 0;

            // 当前页次
            this.pageIndex = op.pageIndex || 1;

            // 计算总页数
            //this.pageNum = Math.ceil(this.totalNum / this.pageSize) || 1;

            // 放置分页的容器
            this.pageCon = op.pageCon;

            // 当前页次文本框
            this.jcurPage = op.pageCon.find(".j-page-cur");

            // 放置总页数的容器
            this.jtotalPage = op.pageCon.find(".j-page-totalPage");

            // 回调函数
            this.callback = op.callback;

            // 执行初始化事件
            this.init();
        };

        // 设置总数量，并重新计算页数
        pageNav.prototype.setTotalNum = function (totalNum) {

            this.totalNum = totalNum || 0;

            // 重新计算页数
            this.pageNum = Math.ceil(this.totalNum / this.pageSize) || 1;

            this.jtotalPage.html(this.pageNum);
        }

        // 设置当前页次为指定值，该操作不会触发回调
        pageNav.prototype.setPageIndex = function (index) {
            this.pageIndex = index;
            this.jcurPage.val(index);
        }

        // 前往某一页，并执行回调
        pageNav.prototype.goToPage = function (index) {

            if (index > this.pageNum) {
                index = this.pageNum;
            } else if (index < 1) {
                index = 1;
            }

            this.pageIndex = index;

            this.setPageIndex(index);

            this.callback(index);
        }

        // 前往下一页
        pageNav.prototype.next = function () {
            if (this.pageIndex >= this.pageNum) { return; }
            this.pageIndex++;
            this.goToPage(this.pageIndex);
        }

        // 前往上一页
        pageNav.prototype.prev = function () {
            if (this.pageIndex <= 1) { return; }
            this.pageIndex--;
            this.goToPage(this.pageIndex);
        }

        // 前往最后一页
        pageNav.prototype.last = function () {
            this.pageIndex = this.pageNum;
            this.goToPage(this.pageIndex);
        }

        // 前往第一页
        pageNav.prototype.first = function () {
            this.pageIndex = 1;
            this.goToPage(this.pageIndex);
        }

        // 绑定事件
        pageNav.prototype.bindEvent = function () {

            var me = this;

            // 点击上一页
            me.pageCon.delegate(".j-page-prev", "click", function () {
                me.prev();
                return false;
            });

            // 点击第一页
            me.pageCon.delegate(".j-page-first", "click", function () {
                me.first();
                return false;
            });

            // 点击下一页
            me.pageCon.delegate(".j-page-next", "click", function () {
                me.next();
                return false;
            });

            // 点击最后一页
            me.pageCon.delegate(".j-page-last", "click", function () {
                me.last();
                return false;
            });
            
            // 回车某一页
            me.pageCon.delegate(".j-page-cur", "keydown", function (e) {
            	if(e.keyCode  == 13){
            		me.goToPage(this.value);
            		return false;
            	}
            });

            // 使页次文本框只能输入数字
            me.jcurPage.bind("textInput", function (e) {
                if (!/^\d+$/.test(e.originalEvent.data)) {
                    return false;
                }
            });
        }

        // 初始化事件
        pageNav.prototype.init = function () {
            this.bindEvent();
            this.setTotalNum(this.totalNum);
        }

        return pageNav;
    })()
});
